package com.xbongbong.util;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.AttrLenthConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;

import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/07/15 16:42
 */
public class ValidateUtil {

    /**
     * 校验金额字段
     * @author 海镔
     * @date 2019/9/24 20:23
     * @param data 数据
     * @param attr 字段标识
     * @param explainMap 字段容器
     * @return void
     * @throws XbbException 业务异常
     */
    public static void validatePayment(JSONObject data, String attr, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        if (!data.containsKey(attr) || Objects.isNull(data.get(attr))){
            FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
            if (Objects.equals(fieldAttrEntity.getRequired(),1)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FIELD_MUST_REQUIRED, fieldAttrEntity.getAttrName());
            }
        }
    }
    /**
     * 校验编号长度且编号存在
     *
     * @param serialNumber 流水号
     * @param sheetNoAttrName 流水号名称
     * @author feng.zheng
     * @date 2019/2/14 22:05
     */
    public static void checkSerialNumber(String serialNumber, String sheetNoAttrName) throws XbbException {
        if (StringUtil.isEmpty(serialNumber)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002.getCode(), ErrorMessageConstant.PLEASE_ENTER, sheetNoAttrName);
        }
        if (serialNumber.length() > AttrLenthConstant.SERIAL_NUMBER_MAX_LENGTH) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015.getCode(), ErrorMessageConstant.LENGTH_OVER_LIMIT, sheetNoAttrName, AttrLenthConstant.SERIAL_NUMBER_MAX_LENGTH);
        }
    }

    /**
     * 校验字段长度
     *
     * @param data 数据
     * @param attr 属性
     * @param attrName 字段名
     * @param length 字段长度
     * @author feng.zheng
     * @date 2019/2/15 20:23
     */
    public static void checkFieldEntityLength(JSONObject data, String attr, String attrName, Integer length) throws XbbException {
        String fieldEntityData = FastJsonHelper.getStringFromFormData(data, attr);
        if (fieldEntityData != null) {
            if (fieldEntityData.length() > length) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015.getCode(), ErrorMessageConstant.LENGTH_OVER_LIMIT, attrName, length);
            }
        }
    }
}
